<?php

namespace App\Services\Common;

use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\FromCollection;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class CommonExcelExport implements FromCollection, WithStyles
{

    //公共导出
    private $row;
    private $data;
    private $datawith;

    public function __construct(array $row, array $data, array $datawith = [])
    {
        $this->row = $row;
        $this->data = $data;
        $this->datawith = $datawith;
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        $row = $this->row;
        $data = $this->data;

        //设置表头
        foreach ($row[0] as $key => $value) {
            $key_arr[] = $key;
        }

        //输入数据
        foreach ($data as $key => &$value) {
            $js = [];
            for ($i = 0; $i < count($key_arr); $i++) {
                $js = array_merge($js, [$key_arr[$i] => $value[$key_arr[$i]] ?? '']);
            }
            array_push($row, $js);
            unset($value);
        }
        return collect($row);
    }

    public function styles(Worksheet $sheet)
    {
        if (count($this->datawith)) {
            foreach ($this->datawith as $key => $val) {
                $sheet->getColumnDimension($key)->setWidth($val);
            }
        }
    }
}
